package com.example.testerclientapp;

import java.io.IOException;
import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class GetReservationList extends Activity {
	private static final String SOAP_ACTION = "http://spartansparking.org/cancelReservation";
	private static final String SOAP_ACTION1 = "http://spartansparking.org/getReservationByEmail";
	private static final String METHOD_NAME =  "cancelReservation";     
	private static final String METHOD_NAME1 =  "getReservationByEmail"; 
	private static final String NAMESPACE =    "http://spartansparking.org/";    
	private static final String URL = "http://spartanparking.azurewebsites.net/parkingservice.asmx";   
	private AndroidHttpTransport mAht;
	public  SoapSerializationEnvelope mSoapEnvelope;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_get_reservation_list);
		////////////////////////// SHOW EXISTING RESERVATIONS BY EMAIL IN TEXT VIEW /////////////////////////
	
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
		Intent getIntentVal = getIntent();
		
		String email = getIntentVal.getStringExtra("email");
        //Toast.makeText(getApplicationContext(), "My email is"+ email, Toast.LENGTH_LONG).show();
        request.addProperty("email", email);
        
        
        
        mSoapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        mSoapEnvelope.dotNet = true;
        mSoapEnvelope.setOutputSoapObject(request);
			
        mAht = new AndroidHttpTransport(URL);
    	
		try {
			mAht.call(SOAP_ACTION1, mSoapEnvelope);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (XmlPullParserException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	   //in-out parameter: soapEnvelope, which means the response back will be stored in this var soapEnvelope
	
	
	 if (mSoapEnvelope.bodyIn instanceof SoapFault)
	 {
		 String str= ((SoapFault) mSoapEnvelope.bodyIn).faultstring;
		 createAndShowDialog(str, "Error in retrieval");
		 
	}
	else 
		 {

				SoapPrimitive resultsRequestSOAP = null;
				try {
					resultsRequestSOAP = (SoapPrimitive)mSoapEnvelope.getResponse();
					
					//Toast.makeText(getApplicationContext(), resultsRequestSOAP.toString(), Toast.LENGTH_LONG).show();
				} catch (SoapFault e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
                 TextView tv= (TextView)findViewById(R.id.textView3);
    		     tv.setText("Your current reservations"+resultsRequestSOAP.toString());
    		     String response1=resultsRequestSOAP.toString();
    		     
    		     ///////////////////////// PARSE AND SHOW CURRENT RESERVATIONS ////////////////////////
    		     
    		     String delim = "<reservation id=";
 				String temp;
 				ArrayList<String> rsvIdFound = new ArrayList<String>();
 				ArrayList<String> costFound = new ArrayList<String>();
 				int startIdx = -1;
 				int endIdx = -1;
 				
 				int chk = response1.indexOf(delim,0);
 				
 				while(chk != -1)
 				{
 					startIdx = chk + delim.length()+1;
 					endIdx = response1.indexOf('\"', startIdx);
 					
 					temp = response1.substring(startIdx, endIdx);
 					rsvIdFound.add(temp);
 					
 					chk = response1.indexOf(delim, endIdx);
 				}
 			
 				// Parse "Total Due" or Parking Cost //
 				delim = "<totaldue>";
 				
 				chk = response1.indexOf(delim,0);
 				
 				while (chk != -1)
 				{
 					startIdx = chk + delim.length()+1;
 					endIdx = response1.indexOf("</totaldue>", startIdx);
 					
 					temp = response1.substring(startIdx, endIdx);
 					costFound.add(temp);
 					
 					chk = response1.indexOf(delim, endIdx);
 				}
 				
 				// Construct the String result that will be shown on the client's User Interface
 				// result will contain Reservation ID and Total Due for each
 				String result = "";
 				for (int i=0; i < rsvIdFound.size(); i++)
 				{
 					result += "Reservation ID: "; 
 					result += rsvIdFound.get(i);
 					result += "  ";
 					result += "Total Due: ";
 					result += costFound.get(i);
 					result += "\n";
 				}
 				
 				tv.setText(result);
    		     
    		     
    		     
    		     /*********************** 
    		     String delim = "<reservation id=";
    				String temp;
    				ArrayList<String> spotIdFound = new ArrayList<String>();
    				ArrayList<String> floorFound = new ArrayList<String>();
    				int startIdx = -1;
    				int endIdx = -1;
    				
    				int chk = response1.indexOf(delim,0);
    				
    				while(chk != -1)
    				{
    					startIdx = chk + delim.length()+1;
    					endIdx = response1.indexOf('\"', startIdx);
    					
    					temp = response1.substring(startIdx, endIdx);
    					spotIdFound.add(temp);
    					//spotIdFound.add(new String("Reservation Id " + temp.charAt(1)));
    					//check the floor number
    					floorFound.add(new String("Reservation Id " + temp.charAt(1)));
    					
    					chk = response1.indexOf(delim, endIdx);
    					
    				}
    				
    				String result = "";
    				for (int i=0; i < spotIdFound.size(); i++)
    				{
    					result += floorFound.get(i);
    					result += ": ";
    					result += spotIdFound.get(i);
    					result += "\n";
    				}
    				
    				tv.setText(result);
    		     **********/
    		     
    		          ///////////////// end of parse function //////////////////////////////// 
    		     
    		     
    			 //createAndShowDialog(resultsRequestSOAP.toString(), "Your current Reservations");	 
    		 }
    		 
    

		////////////////////////////////////////////////// CANCEL RESERVATION /////////////
	
		Button cancel = (Button)findViewById(R.id.button1);
				cancel.setOnClickListener(new View.OnClickListener()
		        {
		        	@Override
		        	public void onClick(View v)
		        	{
		        	 EditText id= (EditText)findViewById(R.id.editText1);
		              String Id = id.getText().toString();
		              int reservationId = Integer.valueOf(Id);

				        if ((Id.length())!= 0)
				        {
				        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
				        //request.addProperty("email", email.getText().toString());
				        request.addProperty("reservationId", reservationId);
				        
				        
				        mSoapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				        mSoapEnvelope.dotNet = true;
				        mSoapEnvelope.setOutputSoapObject(request);
				        
				        mAht = new AndroidHttpTransport(URL);
        	        	
							try {
								mAht.call(SOAP_ACTION, mSoapEnvelope);
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							} catch (XmlPullParserException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						   //in-out parameter: soapEnvelope, which means the response back will be stored in this var soapEnvelope
        	        	
        	        	
        	        	 if (mSoapEnvelope.bodyIn instanceof SoapFault)
        	        	 {
        	        		 String str= ((SoapFault) mSoapEnvelope.bodyIn).faultstring;
        	        		 createAndShowDialog(str, "Login Error");
        	        		 
        	        	}
        	        	else 
        	        		 {
        	       
									SoapPrimitive resultsRequestSOAP = null;
									try {
										resultsRequestSOAP = (SoapPrimitive)mSoapEnvelope.getResponse();
									} catch (SoapFault e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								
        		     
        		        		 if (resultsRequestSOAP.toString().equals("true"))
        		        		 {
        		        			 createAndShowDialog(resultsRequestSOAP.toString(), "Your reservation is cancelled. Status:");
        		        			 
        		        		 }
        		        		 else
        		        		 	{
        		        			 	// return "false" means no user found in database
        		        			 	createAndShowDialog(resultsRequestSOAP.toString(), "Unable to cancel the reservation");
        		        		 	}
        	        		 }
				        
			       
			        }
				        else
				        	Toast.makeText(getApplicationContext(), "Please enter ReservationId", Toast.LENGTH_LONG).show();
			        
		        	}
		        });
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.get_reservation_list, menu);
		return true;
	}

	public void createAndShowDialog(String message, String title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage(message);
		builder.setTitle(title);
		builder.create().show();
	}

	
	
	
}
